package api

import (
	"awesomeProject/internal/config"
	"awesomeProject/internal/middleware"
	"awesomeProject/internal/repository"
	"awesomeProject/internal/service"
	"awesomeProject/pkg/auth"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// SetupRoutes 设置所有路由
func SetupRoutes(r *gin.Engine, db *gorm.DB, cfg *config.Config) {
	// 初始化JWT管理器
	jwtConfig := auth.LoadConfigFromEnv()
	jwtManager := auth.NewJWTManager(jwtConfig.SecretKey, jwtConfig.TokenDuration)
	
	// 静态文件服务 - 必须在其他路由之前
	r.Static("/static", "d:/GO-Project/src/awesomeProject/web/static")
	r.StaticFile("/", "d:/GO-Project/src/awesomeProject/web/index.html")
	r.StaticFile("/index.html", "d:/GO-Project/src/awesomeProject/web/index.html")
	r.StaticFile("/post.html", "d:/GO-Project/src/awesomeProject/web/post.html")
	r.StaticFile("/profile.html", "d:/GO-Project/src/awesomeProject/web/profile.html")

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok"})
	})

	// 初始化仓储层
	userRepo := repository.NewUserRepository(db)
	postRepo := repository.NewPostRepository(db)
	categoryRepo := repository.NewCategoryRepository(db)
	commentRepo := repository.NewCommentRepository(db)

	// 初始化服务层
	userService := service.NewUserService(userRepo, jwtManager)
	aiService := service.NewAIService(&cfg.AI)
	postService := service.NewPostService(postRepo, userRepo, categoryRepo, aiService)
	categoryService := service.NewCategoryService(categoryRepo)
	commentService := service.NewCommentService(commentRepo, postRepo, userRepo)

	// 初始化中间件
	authMiddleware := middleware.AuthMiddleware(jwtManager)
	adminMiddleware := middleware.AdminMiddleware()

	// 初始化控制器
	userController := NewUserController(userService)
	postController := NewPostController(postService)
	categoryController := NewCategoryController(categoryService)
	commentController := NewCommentController(commentService)
	aiController := NewAIController(aiService)

	// API路由组
	api := r.Group("/api/v1")
	{
		// 公开的用户路由（无需认证）
		api.POST("/users/register", userController.Register)
		api.POST("/users/login", userController.Login)

		// Token刷新路由（需要有效token）
		api.POST("/auth/refresh", middleware.AuthMiddleware(jwtManager), userController.RefreshToken)

		// 公开的帖子路由（无需认证）
		api.GET("/posts", postController.ListPosts)
		api.GET("/posts/:id", postController.GetPost)
		api.GET("/posts/category/:categoryId", postController.GetPostsByCategory)

		// 公开的分类路由（无需认证）
		api.GET("/categories", categoryController.ListCategories)
		api.GET("/categories/:id", categoryController.GetCategory)

		// 需要认证的路由组
		auth := api.Group("/").Use(authMiddleware)
		{
			// 用户相关的认证路由
			auth.GET("/users/profile", userController.GetProfile)
			auth.PUT("/users/profile", userController.UpdateProfile)
			auth.PUT("/users/password", userController.ChangePassword)
			auth.DELETE("/users/account", userController.DeleteAccount)
			auth.GET("/users/:user_id/favorites", postController.GetUserFavorites)

			// 帖子相关的认证路由
			auth.POST("/posts", postController.CreatePost)
			auth.PUT("/posts/:id", postController.UpdatePost)
			auth.DELETE("/posts/:id", postController.DeletePost)
			auth.POST("/posts/:id/favorite", postController.AddFavorite)
			auth.DELETE("/posts/:id/favorite", postController.RemoveFavorite)
		}

		// 需要管理员权限的路由组
		admin := api.Group("/admin").Use(authMiddleware, adminMiddleware)
		{
			// 用户管理
			admin.GET("/users", userController.ListUsers)

			// 分类管理
			admin.POST("/categories", categoryController.CreateCategory)
			admin.PUT("/categories/:id", categoryController.UpdateCategory)
			admin.DELETE("/categories/:id", categoryController.DeleteCategory)
		}

		// 评论相关路由
		comments := api.Group("/comments")
		{
			comments.POST("", commentController.CreateComment) // 需要认证
			comments.PUT("/:id", commentController.UpdateComment) // 需要认证
			comments.DELETE("/:id", commentController.DeleteComment) // 需要认证
			comments.GET("/post/:post_id", commentController.GetCommentsByPost)
		}

		// AI相关路由
		ai := api.Group("/ai")
		{
			ai.POST("/classify", aiController.AutoClassify)
			ai.POST("/summary", aiController.GenerateSummary)
			ai.POST("/qa", aiController.AnswerQuestion)
			ai.POST("/embedding", aiController.GenerateEmbedding)
		}
	}
}